import { login } from '../../apis/api/index';
import { DeviceManager } from '../../utils/util'
const app = getApp()

Page({
  data: {
    loading: false,
    showPrivacyPopup: false,
    privacyAgreed: false
  },

  onLoad() {
    // 监听隐私授权需求
    if (wx.onNeedPrivacyAuthorization) {
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('需要隐私授权');
        this.setData({
          showPrivacyPopup: true
        });
        // 保存resolve函数到页面实例
        this.resolvePrivacyAuthorization = resolve;
      });
    }
  },
  // 隐私政策同意
  onPrivacyAgree() {
    this.setData({
      privacyAgreed: true,
      showPrivacyPopup: false
    });
  },

  // 隐私政策拒绝
  onPrivacyReject() {
    this.setData({
      privacyAgreed: false,
      showPrivacyPopup: false
    });
  },

  // 获取手机号回调
  async onGetPhoneNumber(e) {
    // 检查是否同意隐私政策
    if (!this.data.privacyAgreed) {
      wx.showToast({
        title: '请先同意隐私政策',
        icon: 'none'
      });
      this.setData({
        showPrivacyPopup: true
      });
      return;
    }
    
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'error'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 获取微信登录code
      const loginRes = await this.getWxLoginCode();
      if (!loginRes.success || !loginRes.code) {
        throw new Error('微信登录失败');
      }
      // 使用手机号和code获取token
      const data = await login({
        code: e.detail.code,
        deviceId: app.globalData.deviceId
      });

        wx.setStorageSync('user', data.user)
        wx.setStorageSync('token', data.accessToken)
        wx.setStorageSync('refreshToken', data.refreshToken)
        app.globalData.user = data.user
        app.globalData.token = data.accessToken
        app.globalData.refreshToken = data.refreshToken
        wx.reLaunch({
          url: '/pages/index/index'
        })

    } catch (error) {
      console.error('登录失败:', error);
      wx.showToast({
        title: error.message || '登录失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 获取微信登录code
  getWxLoginCode() {
    return new Promise((resolve) => {
      wx.login({
        success: (res) => {
          resolve({ success: true, code: res.code });
        },
        fail: () => {
          resolve({ success: false });
        }
      });
    });
  },


  // 显示隐私政策
  showPrivacyPolicy() {
    this.setData({
      showPrivacyPopup: true
    });
  }
}); 
